package com.cgy.utils.base.dynamic;

import java.lang.reflect.Method;

import com.cgy.utils.base.dynamic.handler.AgencyHandler;

import lombok.Getter;
import lombok.Setter;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

/**
 * @author CH
 */
public class DynamicInterceptor<T> implements MethodInterceptor {

    private Class<?> agencyClass;

    private AgencyHandler agencyHandler;

    private ClassLoader classLoader;

    @Getter
    @Setter
    private T t;

    /**
     *
     * @param agencyClass
     */
    public DynamicInterceptor(Class<?> agencyClass, ClassLoader classLoader, AgencyHandler agencyHandler) {
        this.agencyClass = agencyClass;
        this.agencyHandler = agencyHandler;
        this.classLoader = classLoader;
        this.t = newInstance();
    }

    /**
     * 实例化
     * @return
     */
    @SuppressWarnings("unchecked")
	public T newInstance() {
        Enhancer enhancer = new Enhancer();
        enhancer.setCallback(this);
        enhancer.setSuperclass(this.agencyClass);
        if(null == classLoader) {
            classLoader = ClassLoader.getSystemClassLoader();
        }

        enhancer.setClassLoader(classLoader);

        return (T) enhancer.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        if(null != agencyHandler) {
            agencyHandler.before();
        }


        if(null != agencyHandler) {
            objects = agencyHandler.aroundBefore(objects);
        }

        Object o1 = methodProxy.invokeSuper(o, objects);

        if(null != agencyHandler) {
            o1 = agencyHandler.aroundAfter(o1);
        }

        if(null != agencyHandler) {
            agencyHandler.after(method, objects);
        }

        return o1;
    }
}
